<template>
  <div>
    <div v-if="topInputShow">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="小区名称" style="font-weight: bolder">
          <el-input v-model="communityName" size="small" placeholder="请输入小区名称"></el-input>
        </el-form-item>
        <el-form-item label="小区编码" style="font-weight: bolder">
          <el-input v-model="communityCode" size="small" placeholder="请输入小区编码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="loadCommunity(1)" size="small" style="background-color: #23C6C8" icon="el-icon-search"
                     type="success">查询
          </el-button>
          <el-button icon="el-icon-refresh" size="small" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-row class="btn">
      <el-button icon="el-icon-plus" type="primary" @click="addCommunity(),dialogCommunityVisible=true" size="mini">
        新增
      </el-button>
      <el-button icon="el-icon-edit" type="success" size="mini" @click="update()" :disabled="single">修改</el-button>
      <el-button icon="el-icon-delete" @click="deleteCommunities" type="danger" size="mini" :disabled="multiple">删除
      </el-button>
      <el-button icon="el-icon-download" @click="outExe" type="warning" size="mini">导出</el-button>
    </el-row>
    <el-row class="btn-circle">
      <el-button icon="el-icon-search" size="mini" circle @click="topInputShows"></el-button>
      <el-button icon="el-icon-refresh" size="mini" circle @click="refresh"></el-button>
    </el-row>
    <el-table
        :data="communities"
        border
        id="tableId"
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55"
          align="center">
      </el-table-column>
      <el-table-column
          label="序号"
          width="180"
          align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.communityId }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="小区名称"
          width="120"
          align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.communityName }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="小区编码"
          width="230"
          align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.communityCode }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="省"
          width="170"
          align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.sysProvenceArea.name }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="市"
          width="170"
          align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.sysCityArea.name }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="区/县"
          width="170"
          align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.sysTownArea.name }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="创建时间"
          width="180"
          align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="备注"
          width="120"
          align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button icon="el-icon-edit" @click="showCommunity(scope.row),dialogCommunityVisible=true" type="text">
            修改
          </el-button>
          <el-button icon="el-icon-delete" @click="tips(scope.row.communityId)" type="text">删除</el-button>
          <el-button icon="el-icon-setting" @click="replaceProperty(scope.row),dialogPropertyVisible=true" type="text">
            更换物业
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        class="page"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[size]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>

    <el-dialog :title="title" :visible.sync="dialogCommunityVisible" class="addRoleDialog" width="500px">
      <el-form label-width="100px" :model="community" :rules="formRules" ref="form">
        <el-form-item label="小区名称" :required="true" prop="communityName">
          <el-input v-model="community.communityName" placeholder="请输入小区名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="详细地址" :required="true" prop="communityDetailedAddress">
          <el-input v-model="community.communityDetailedAddress" placeholder="请输入详细地址" clearable></el-input>
        </el-form-item>
        <el-form-item label="所属区划" :required="true">
          <el-cascader style="float: left"
                       :options="areaList"
                       :props="defaultParams"
                       v-model="selectedOptions"
                       clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4}"
              placeholder="请输入内容"
              v-model="community.remark">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCommunityVisible=false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="更换物业" :visible.sync="dialogPropertyVisible" class="addRoleDialog" width="650px">
      <el-table
          :data="depts"
          style="width: 100%;margin-bottom: 20px;"
          row-key="deptId"
          default-expand-all
          :tree-props="{children: 'childDept', hasChildren: 'hasChildren'}">
        <el-table-column
            prop="deptName"
            label="部门名称"
            width="150">
        </el-table-column>
        <el-table-column
            prop="status"
            label="状态"
            width="120">
          <template slot-scope="scope">
            <label v-if="scope.row.status==0">正常</label>
            <label v-if="scope.row.status==1">停用</label>
          </template>
        </el-table-column>
        <el-table-column
            prop="createTime"
            label="创建时间"
            width="180">
        </el-table-column>
        <el-table-column
            label="操作"
            width="120">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="text"
                v-if="scope.row.parentId == 100 && scope.row.deptId != selectedDeptId"
                icon="el-icon-success"
                @click="replacePropertyAction(scope.row)"
                v-hasPermi="['system:dept:add']"
            >选择
            </el-button>
            <el-button
                size="mini"
                type="text"
                v-else-if="scope.row.deptId == selectedDeptId"
                icon="el-icon-success"
            >已选择
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>


  </div>
</template>

<script>
import FileSaver from "file-saver";
import * as XLSX from "xlsx";

export default {
  name: "ZyCommunityView",
  data() {
    return {
      communities: null,
      current: 1,
      size: 5,
      pages: 0,
      total: 0,
      title:"",
      communityName: "",   //小区名称
      communityCode: "",   //小区编码
      single: true,       // 非单个禁用
      multiple: true,     // 非多个禁用
      topInputShow: true,  //搜索框默认显示
      dialogCommunityVisible: false, //弹出框默认不显示
      dialogPropertyVisible: false,  //默认更换物业不弹出
      areaList: [],    //城市的树状结构数据
      selectedOptions: [],  //选中的区划信息
      ids: [],    // 选中数组
      creatCommunity: "",
      depts: null,
      comId:"",
      publicCommunityId: "",
      selectedDeptId: "",
      defaultParams: {
        label: 'name',
        value: 'code',
        children: 'childArea',
      },
      deptTree: {
        value: "deptId",
        label: "deptName",
        children: "children",
      },
      formRules:{
        communityName:[
          {required: true,message: "小区名称不能为空",trigger: "blur"},
        ],
        communityDetailedAddress:[
          {required: true,message: "详细地址不能为空",trigger: "blur"},
        ],
        selectedOptions:[
          {required: true,message: "所属区域不能为空",trigger: "blur"},
        ]
      },
      community: {
        communityId: "0",
        communityName: "",
        communityCode: "",
        communityProvenceCode: "",
        communityCityCode: "",
        communityTownCode: "",
        communityDetailedAddress: "",
        communityLongitude: "",
        communityLatitude: "",
        deptId: "",
        communitySort: "",
        createBy: "",
        createTime: "",
        updateBy: "",
        updateTime: "",
        remark: ""
      }
    }
  },
  methods: {
    loadCommunity(current) {
      this.axios.get("zyCommunity-page?current=" + this.current + "&size=" + this.size + "&communityName=" + this.communityName + "&communityCode=" + this.communityCode + "&communityId=" + this.comId)
          .then(res => {
            this.communities = res.data.data.records;
            this.pages = res.data.data.pages;
            this.total = res.data.data.total;
          })
      this.axios.get("area-tree")
          .then(res => {
            this.areaList = this.getTreeData(res.data.data);
          })
      this.axios.get("dept-tree")
          .then(result => {
            this.depts = result.data.data;

          })
    },
    handleSizeChange(size) {
      console.log(size);
    },
    replaceProperty(com) {
      this.selectedDeptId = com.deptId;
      this.publicCommunityId = com.communityId;
      this.creatCommunity = JSON.parse(JSON.stringify(com));
      console.log(this.publicCommunityId);
    },
    handleCurrentChange(val) {
      console.log(val);
      this.current = val;
      this.loadCommunity();
    },
    // 递归判断列表，把最后的children设为undefined
    getTreeData(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].childArea.length < 1) {
          // children若为空数组，则将children设为undefined
          data[i].childArea = undefined;
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].childArea);
        }
      }
      return data;
    },
    //导出excel表格
    outExe() {
      this.$confirm("此操作将导出excel文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            this.excelData = this.communities; //你要导出的数据list。
            this.exportExcel();
          })
          .catch(() => {
          });
    },
    exportExcel() {
      //转换成excel时，使用原始的格式
      var xlsxParam = {raw: true};
      let fix = document.querySelector(".el-table__fixed");
      let wb;
      //判断有无fixed定位，如果有的话去掉，后面再加上，不然数据会重复
      if (fix) {
        wb = XLSX.utils.table_to_book(
            document.querySelector("#tableId").removeChild(fix), xlsxParam);
        document.querySelector("#tableId").appendChild(fix);
      } else {
        wb = XLSX.utils.table_to_book(document.querySelector("#tableId"), xlsxParam);
      }
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(new Blob([wbout], {type: "application/octet-stream"}), "导出详情单.xlsx");
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    //点击添加按钮
    addCommunity() {
      this.selectedOptions = "";
      this.nullCommunity();
      this.title = "添加小区信息"
    },
    //点击修改按钮
    showCommunity(community) {
      this.title="修改小区信息"
      this.community = JSON.parse(JSON.stringify(community));
    },
    // //点击保存按钮
    // save() {
    //   if (this.community.communityId == 0) {
    //     this.axios.post("zyCommunity/", {zyCommunity: this.community, areaList: this.selectedOptions})
    //         .then(res => {
    //           if (res.data.code == 200) {
    //             this.loadCommunity(this.current);
    //           }
    //         })
    //   } else {
    //     this.axios.put("zyCommunity/", {zyCommunity: this.community, areaList: this.selectedOptions})
    //         .then(res => {
    //           if (res.data.code == 200) {
    //             this.loadCommunity(this.current);
    //           }
    //         })
    //   }
    //   this.dialogCommunityVisible = false;
    // },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.community.communityId == 0) {
            this.axios.post("zyCommunity/", {zyCommunity: this.community, areaList: this.selectedOptions})
                .then(res => {
                  if (res.data.code == 200) {
                    this.loadCommunity(this.current);
                  }
                })
          } else {
            this.axios.put("zyCommunity/", {zyCommunity: this.community, areaList: this.selectedOptions})
                .then(res => {
                  if (res.data.code == 200) {
                    this.loadCommunity(this.current);
                  }
                })
          }
          this.dialogCommunityVisible = false;
        } else {
          alert('表单校验不通过')
          return false;
        }
      });
    },
    //点击重置按钮
    reset() {
      this.communityName = "";
      this.communityCode = "";
      this.$router.go(0);
    },
    //隐藏搜索框
    topInputShows() {
      this.topInputShow = !this.topInputShow;
    },
    //刷新
    refresh() {
      this.$router.go(0)
    },
    //复选框的选择、选择一个时修改和删除按钮都显示 、 选择两个的时候只显示删除
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.communityId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    //多选框选择后点击修改
    update() {
      this.axios.get("community/" + this.ids)
          .then(res => {
            console.log(res.data.data);
            this.community = res.data.data;
          })
      this.dialogCommunityVisible = true;
    },
    //删除判断
    tips(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!',
        });
        this.deleteCommunity(id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //更换物业选择方法
    replacePropertyAction(row) {
      console.log(this.publicCommunityId);
      this.$confirm('是否确认更换成该物业?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
            if(this.creatCommunity.communityId != 0){
              this.axios.put("updateCommunity/", {publicCommunityId:this.publicCommunityId,deptId:row.deptId,community:this.creatCommunity}).then(response => {
                this.dialogPropertyVisible = false;
                this.loadCommunity(this.current);
              })
            }
          }).catch(() => {
      });
    },
    //删除功能
    deleteCommunity(id) {
      console.log(id);
      this.axios.delete("zyCommunity/" + id)
          .then(res => {
            if (res.data.code == 200) {
              this.loadCommunity(this.current);
            }
          })
    },
    //批量删除
    deleteCommunities() {
      this.axios.delete("communities/" + this.ids)
          .then(res => {
            if (res.data.code == 200) {
              this.loadCommunity(this.current);
            }
          })
    },
    nullCommunity() {
      this.community = {
        communityId: "0",
        communityName: "",
        communityCode: "",
        communityProvenceCode: "",
        communityCityCode: "",
        communityTownCode: "",
        communityDetailedAddress: "",
        communityLongitude: "",
        communityLatitude: "",
        deptId: "",
        communitySort: "",
        createBy: "",
        createTime: "",
        updateBy: "",
        updateTime: "",
        remark: ""
      }
    },
    // 联动
    setCurrentZyCommunity(id){
      this.comId=id
      this.loadCommunity(1)
    }
  },
  mounted() {
    this.loadCommunity(1);
    // 联动
    this.$bus.$on('mainCurrentCommunityChange',(id)=>{
      this.setCurrentZyCommunity(id)
    });
  }
}
</script>

<style scoped>
.page {
  float: right;
  margin-top: 30px;
}

.btn {
  float: left;
  margin-bottom: 10px;
}

.btn-circle {
  float: right;
}

.demo-form-inline {
  position: relative;
  left: -445px;
}

.num {
  position: relative;
  left: -300px;
}

.radio {
  position: relative;
  left: -300px;
}

.tree {
  position: relative;
  left: 10px;
  width: 500px;
}

.tree-border {
  border: 1px solid wheat;
  padding: 10px 0 10px 10px;
  width: 400px;
}

.check {
  position: relative;
  left: -220px;
}
</style>